package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.common.Constant;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenlongStart
 * @create 2021-06-28 17:14
 * @desc
 */
public class JDBCUtil {

    public static Connection getJdbcConnection(String phoenixDriver, String phoenixUrl) throws SQLException, ClassNotFoundException {
        Class.forName(phoenixDriver);
        return DriverManager.getConnection(phoenixUrl);
    }
//    public static void main(String[] args) throws Exception {
//        Connection conn = getJdbcConnection(Constant.MYSQL_DRIVER, Constant.MYSQL_URL);
//        List<JSONObject> list = queryList(conn, "select * from user_info where id='1'", null, JSONObject.class);
//        for (JSONObject obj : list) {
//
//            System.out.println(obj);
//        }
//    }

    public static <T> List<T> queryList(Connection conn, String sql, Object[] args,Class<T> tClass) throws Exception {

        // 1、获取prepare对象
        PreparedStatement ps = conn.prepareStatement(sql);

        // 2、给占位符赋值
        for (int i = 0;args!=null && i < args.length; i++) {
            ps.setObject(i+1,args[i]);
        }

        //3、执行sql语句，得到结果集
        ResultSet resultSet = ps.executeQuery();

        //4、通过 resultSet 获取相关的元数据类得到
        ResultSetMetaData metaData = resultSet.getMetaData();
        //5、创建一个list集合，收集每行的结果，最后返回
        List<T> result = new ArrayList<>();

        //6、遍历结果集
        while (resultSet.next()){

            //6.1 遍历到每行数据, 把这些数据封装到 T 类型的对象中
            T t = tClass.newInstance();

            // 得到属性名和属性值
            // 遍历每一列
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnLabel(i+1);// 列的索引是从1开始
                Object value = resultSet.getObject(columnName);
                BeanUtils.setProperty(t,columnName,value);
            }
            result.add(t);
        }

        return result;
    }
}
